Imports Microsoft.VisualBasic
Imports System
Imports System.Windows.Forms
Imports Cforge.Net.Mail
Imports Cforge.Net.Mime
Imports System.IO
Imports Global_Visas_Business_Layer
Imports System.Text
Imports Global_Visas_Business_Layer.TasksEvents

Namespace ImapClientDemo
    Partial Public Class MessageViewer
        Inherits Form
        Private ReadOnly _client As Cforge.Net.Mail.ImapClient
        Private ReadOnly _uniqueId As String
        Private _msg As MailMessage
        Private _abort As Boolean
        Public Shared EventType As String
        Public Sub New()
            InitializeComponent()
        End Sub

        Public Sub New(ByVal client As Cforge.Net.Mail.ImapClient, ByVal uniqueId As String)
            InitializeComponent()

            _client = client
            _uniqueId = uniqueId
        End Sub

        ''' <summary>
        ''' Handles the form's Load event.
        ''' </summary>
        ''' <param name="e"></param>
        Protected Overrides Sub OnLoad(ByVal e As EventArgs)
            MyBase.OnLoad(e)

            ' Disable the X button.
            Util.EnableCloseButton(Me, False)
        End Sub

        ''' <summary>
        ''' Handles the form's Shown event.
        ''' </summary>
        ''' <param name="e">The even arguments.</param>
        Protected Overrides Sub OnShown(ByVal e As EventArgs)
            MyBase.OnShown(e)

            Try
                AddHandler _client.Progress, AddressOf _client_Progress

                ' Create a new memory stream to store the downloaded message.
                Dim mem As New MemoryStream()
                ' Get message data to the newly created memory stream.
                _client.GetMessage(_uniqueId, mem)
                ' Create a new message from the memory stream.
                mem.Seek(0, SeekOrigin.Begin)
                ' Get raw data;
                Dim rawData() As Byte = mem.ToArray()

                _msg = New MailMessage(mem)

                ' Fill from, to, cc.
                txtFrom.Text = _msg.From.ToString()
                txtTo.Text = _msg.To.ToString()
                txtCc.Text = _msg.Cc.ToString()

                ' Fill subject.
                txtSubject.Text = _msg.Subject

                saveAsToolStripMenuItem.Enabled = True
                exitToolStripMenuItem.Enabled = True
                copyToolStripMenuItem.Enabled = True
                selectAllToolStripMenuItem.Enabled = True
                Util.EnableCloseButton(Me, True)

                ' Fill the attachment list.
                If _msg.Attachments.Count > 0 Then
                    For Each at As Attachment In _msg.Attachments
                        cbxAttachment.Items.Add(at.FileName)
                    Next at
                End If

                If cbxAttachment.Items.Count > 0 Then
                    cbxAttachment.SelectedIndex = 0
                    saveAttachmentsToolStripMenuItem.Enabled = True
                Else
                    cbxAttachment.Enabled = False
                    saveAttachmentsToolStripMenuItem.Enabled = False
                End If

                ' Fill body plain text version.
                txtBody.Text = _msg.BodyText.Replace(Constants.vbLf, Constants.vbCrLf)
                ' Fill body HTML version.
                txtHtml.Text = _msg.BodyHtml.Replace(Constants.vbLf, Constants.vbCrLf)

                Dim headers As MimeHeaderCollection = _msg.Headers

                ' Show all message header
                For i As Integer = 0 To headers.Count - 1
                    Dim header As MimeHeader = headers(i)

                    ' add name column
                    Dim item As New ListViewItem(header.Name)

                    ' add header raw content column
                    item.SubItems.Add(header.RawText)

                    ' show unparsed (corrupted) headers in red				
                    If header.IsUnparsable Then
                        item.ForeColor = System.Drawing.Color.Red
                    End If

                    ' add row to the ListView				
                    lvwHeaders.Items.Add(item)
                Next i

                ' Fill raw message.
                Dim text As String = System.Text.Encoding.Default.GetString(rawData, 0, Math.Min(rawData.Length, 500000))
                txtRawText.Text = text
            Catch exc As Exception
                If (Not _abort) Then
                    Util.ShowError(exc)
                Else
                    Me.DialogResult = System.Windows.Forms.DialogResult.Abort
                End If

                Me.Close()
            Finally
                ' Unregister the Progress event handler.
                RemoveHandler _client.Progress, AddressOf _client_Progress
                toolStripProgressLabel.Visible = False
                toolStripProgressBar.Visible = False
                toolStripProgressCancelButton.Visible = False
                toolStripStatusLabel.Visible = True
            End Try
        End Sub

        Private Sub _client_Progress(ByVal sender As Object, ByVal e As ImapProgressEventArgs)
            If (Not IsDisposed) Then
                Invoke(New ImapProgressEventHandler(AddressOf Progress), sender, e)
            End If
        End Sub

        ''' <summary>
        ''' Handles the client's Progress event.
        ''' </summary>
        ''' <param name="sender">The imap client object.</param>
        ''' <param name="e">The event arguments.</param>
        Private Sub Progress(ByVal sender As Object, ByVal e As ImapProgressEventArgs)
            toolStripProgressLabel.Text = String.Format("{0}/{1} downloaded", Util.FormatSize(e.BytesTransferred), Util.FormatSize(e.BytesTotal))
            Application.DoEvents()
        End Sub

        ''' <summary>
        ''' Shows Save as dialog and save the message to the specified file.
        ''' </summary>
        Private Sub SaveMessageAs()
            Dim dlg As New SaveFileDialog()
            Try
                dlg.OverwritePrompt = True
                dlg.Filter = "Email files (*.eml)|*.eml|All files (*.*)|*.*"
                dlg.FilterIndex = 1
                dlg.Title = "Save the mail as"
                ' Show the Save File As dialog.
                If dlg.ShowDialog() <> System.Windows.Forms.DialogResult.OK Then
                    Return
                End If
            Catch
                MessageBox.Show(dlg.FileName & " is not an email file", "Error")
            End Try

            SaveMessageAs(dlg.FileName)
        End Sub

        ''' <summary>
        ''' Saves the current message as a file.
        ''' </summary>
        ''' <param name="fileName"></param>
        Private Sub SaveMessageAs(ByVal fileName As String)
            Try
                _msg.Save(fileName)
            Catch exc As Exception
                Util.ShowError(exc)
            End Try
        End Sub

        ''' <summary>
        ''' Saves attachments to a specific folder.
        ''' </summary>
        Private Sub SaveAttachmentAs(ByVal folder As String)
            Try
                For Each att As Attachment In _msg.Attachments
                    att.Save(Path.Combine(folder, att.FileName))
                Next att
            Catch exc As Exception
                Util.ShowError(exc)
            End Try
        End Sub

        ''' <summary>
        ''' Saves attachments to a specific folder. A browing folder dialog will be shown.
        ''' </summary>
        Private Sub SaveAttachmentAs()
            Dim folderBrowserDialog As New FolderBrowserDialog()
            If folderBrowserDialog.ShowDialog() <> System.Windows.Forms.DialogResult.OK Then
                Return
            End If

            Dim path As String = folderBrowserDialog.SelectedPath
            SaveAttachmentAs(path)
        End Sub

        Private Sub selectAllToolStripMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs) Handles selectAllToolStripMenuItem.Click
            txtBody.SelectAll()
        End Sub

        Private Sub saveAsToolStripMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs) Handles saveAsToolStripMenuItem.Click
            SaveMessageAs()
        End Sub

        Private Sub saveAttachmentsToolStripMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs) Handles saveAttachmentsToolStripMenuItem.Click
            SaveAttachmentAs()
        End Sub

        Private Sub exitToolStripMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs) Handles exitToolStripMenuItem.Click
            Me.Close()
        End Sub

        Private Sub copyToolStripMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs) Handles copyToolStripMenuItem.Click
            txtBody.Copy()
        End Sub

        Private Sub toolStripProgressCancelButton_ButtonClick(ByVal sender As Object, ByVal e As EventArgs) Handles toolStripProgressCancelButton.ButtonClick
            ' Abort the operation.
            _abort = True
            _client.Abort()
        End Sub

        Private Sub btnAddEvent_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddEvent.Click
            Dim TasksEvents As New TasksEvents
            Dim strRecorSend As String = ""
            Dim blnDocsAdded As Boolean
            Dim strMessage As String
            Dim frm As ImapClient_Event
            ' load attachments to docstore
            Try

            
                frm = New ImapClient_Event
                frm.ShowDialog()
                strRecorSend = EventType
                'If rdoInbox.Checked = True Then
                '    strRecorSend = "Email Received"
                'Else
                '    strRecorSend = "Email Sent"
                'End If
                Select Case Me.chkLoadAttachments.Checked
                    Case True
                        If Me.txtBody.Text.Trim.ToString <> "" Then
                            'If CType(Me.grdInbox.CurrentRow, Xceed.Grid.CellRow).Cells(3).Value() > 0 Then
                            '    If MsgBox("This email has no message." & vbCrLf & "Would you like to continue adding attachments to the document store?", MsgBoxStyle.YesNo, "No Message") = MsgBoxResult.No Then
                            '        Exit Sub
                            '    End If
                            'End If
                            ' If CType(Me.grdInbox.CurrentRow, Xceed.Grid.CellRow).Cells(3).Value() > 0 Then
                            'Dim Msg As New StringBuilder
                            ' Call GetMessageMAPIAttachments(CType(Me.grdInbox.CurrentRow, Xceed.Grid.CellRow).Cells(4).Value())
                            'End If
                            If cbxAttachment.Items.Count > 0 Then
                                AddAttachmentsToStore()
                                'If Directory.Exists("H:\TempAttachments") = False Then
                                '    Directory.CreateDirectory("H:\TempAttachments")
                                'End If
                                'Try
                                '    For Each att As Attachment In _msg.Attachments
                                '        att.Save(Path.Combine("H:\TempAttachments\", att.FileName))
                                '    Next att
                                'Catch exc As Exception
                                '    Util.ShowError(exc)
                                'End Try
                            End If
                            blnDocsAdded = True
                            'Me.Dispose()
                            'If Me.txtEventNote.Text.ToString <> "" Then
                            '    strMessage = Me.txtEventNote.Text.ToString & vbCrLf & vbCrLf & "---------------------------------------------------------------" & vbCrLf & vbCrLf & Me.txtMessage.Text.ToString
                            'Else
                            strMessage = "From : " & Me.txtFrom.Text & vbCrLf & vbCrLf & "To : " & txtTo.Text & vbCrLf & vbCrLf & "CC : " & txtCc.Text & vbCrLf & vbCrLf & "Body:" & vbCrLf & Me.txtBody.Text.ToString
                            'End If
                            'strDate = GetEmailArrivalDate(CType(Me.grdInbox.CurrentRow, Xceed.Grid.CellRow).Cells(4).Value())
                            TasksEvents.GblFunc_Add_Event(strRecorSend, strMessage, TasksEvents.EventStatus.SingleEvent, GlobalCRM.CurrentCaseID, EventTypes.EventCase, , , , , , CommonDataFunctions.GetLocalServer) ' DateTime.Now)
                            MsgBox("The email has been added as event and the documents are stored in Document Store.", MsgBoxStyle.OkOnly, "Success")
                        ElseIf Me.txtBody.Text.Trim.ToString = String.Empty Then
                            If cbxAttachment.Items.Count > 0 Then

                                If MsgBox("This email has no message." & vbCrLf & "Would you like to continue adding attachments to the document store?", MsgBoxStyle.YesNo, "No Message") = MsgBoxResult.No Then
                                    Exit Sub
                                Else
                                    'Call GetMessageMAPIAttachments(CType(Me.grdInbox.CurrentRow, Xceed.Grid.CellRow).Cells(4).Value())
                                    'blnDocsAdded = True
                                    'If Me.txtEventNote.Text.ToString <> "" Then
                                    '    strMessage = Me.txtEventNote.Text.ToString & vbCrLf & vbCrLf & "---------------------------------------------------------------" & vbCrLf & vbCrLf & Me.txtMessage.Text.ToString
                                    'Else
                                    '    strMessage = Me.txtMessage.Text.ToString
                                    'End If
                                    'strDate = GetEmailArrivalDate(CType(Me.grdInbox.CurrentRow, Xceed.Grid.CellRow).Cells(4).Value())
                                    TasksEvents.GblFunc_Add_Event(strRecorSend, strMessage, TasksEvents.EventStatus.SingleEvent, GlobalCRM.CurrentCaseID, EventTypes.EventCase, , , , , , CommonDataFunctions.GetLocalServer) 'DateTime.Now)
                                    MsgBox("The email has been added as event and the documents are stored in Document Store.", MsgBoxStyle.OkOnly, "Success")
                                    Exit Sub
                                End If
                            Else
                                MsgBox("This email has no message.", MsgBoxStyle.OkOnly, "No message")
                            End If

                            Exit Sub
                        End If
                    Case False

                        strMessage = "From : " & Me.txtFrom.Text & vbCrLf & vbCrLf & "To : " & txtTo.Text & vbCrLf & vbCrLf & "CC : " & txtCc.Text & vbCrLf & vbCrLf & "Body:" & vbCrLf & Me.txtBody.Text.ToString

                        'strDate = GetEmailArrivalDate(CType(Me.grdInbox.CurrentRow, Xceed.Grid.CellRow).Cells(4).Value())
                        TasksEvents.GblFunc_Add_Event(strRecorSend, strMessage, TasksEvents.EventStatus.SingleEvent, GlobalCRM.CurrentCaseID, EventTypes.EventCase, , , , , , CommonDataFunctions.GetLocalServer) 'DateTime.Now)
                        MsgBox("The email has been added as event.", MsgBoxStyle.OkOnly, "Success")
                End Select

            Catch ex As Exception
            Finally
                frm = Nothing
                TasksEvents = Nothing
            End Try

        End Sub

        Private Function AddAttachmentsToStore() As Boolean
            Dim DocStoreId As Long
            Try

                Directory.CreateDirectory(System.IO.Path.GetTempPath & "CRMTemp")
                For Each objAttach As Attachment In _msg.Attachments
                    '        att.Save(Path.Combine("H:\TempAttachments\", att.FileName))
                    '    Next att
                    'For Each objAttach In colattach
                    If Not objAttach Is Nothing Then
                        DocStoreId = Letters.GblFunc_Create_DocStore(objAttach.FileName, "Loaded as Email Event", GlobalCRM.CurrentCaseID)
                        'objAttach.SaveAsFile(System.IO.Path.GetTempPath & "CRMTemp" & "\" & objAttach.FileName)
                        objAttach.Save(System.IO.Path.GetTempPath & "CRMTemp" & "\" & objAttach.FileName)
                        Letters.GblFunc_Add_FileToStore(System.IO.Path.GetTempPath & "CRMTemp" & "\" & objAttach.FileName, objAttach.FileName, DocStoreId)
                        ''Dim fso As New Scripting.FileSystemObject
                        'fso.DeleteFile(System.IO.Path.GetTempPath & "CRMTemp\" & objAttach.FileName, True)
                        'System.IO.File.Delete(System.IO.Path.GetTempPath & "CRMTemp\" & objAttach.FileName)
                    End If
                Next
                'Directory.Delete(System.IO.Path.GetTempPath & "CRMTemp\")

                DeleteDirContents(New IO.DirectoryInfo(System.IO.Path.GetTempPath & "CRMTemp\"))

                Return True
            Catch ex As Exception
                MsgBox("Error in Attaching the documents. Please contact IT", MsgBoxStyle.Information, "Attachments")
                Return False
            End Try
        End Function
        Public Sub DeleteDirContents(ByVal dir As IO.DirectoryInfo)
            Try

                Dim fa() As IO.FileInfo
                Dim f As IO.FileInfo

                fa = dir.GetFiles

                For Each f In fa
                    f.Delete()
                Next

                Dim da() As IO.DirectoryInfo
                Dim d1 As IO.DirectoryInfo

                da = dir.GetDirectories
                For Each d1 In da
                    DeleteDirContents(d1)
                Next
                dir.Delete()

            Catch ex As Exception

            End Try
        End Sub

        Private Sub btnReply_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReply.Click
            ' reply to the selected email

            'Dim sbBody As New StringBuilder
            'Try
            '    'If grdInbox.SelectedItems.Count = 0 Then
            '    '    CommonFuncs.DisplayMessage("Please select an email.", CommonDialog.CustomDialogIcons.Information, "Info")
            '    '    Exit Sub
            '    'End If
            '    If GlobalCRM.CurrentCompanyID > 0 Then
            '        If GlobalCRM.CurrentContactID > 0 Then
            '            If (MsgBox("Would you like to reply to the contact? ; selecting NO would send a reply to candidate.", MsgBoxStyle.YesNo, "Email To") = MsgBoxResult.Yes) Then
            '                'frmSendEmail.iEmailType = frmSendEmail.EmailType.Contact
            '            Else
            '                'frmSendEmail.iEmailType = frmSendEmail.EmailType.Candidate
            '            End If
            '        Else
            '            'frmSendEmail.iEmailType = frmSendEmail.EmailType.Candidate
            '        End If
            '    Else
            '        'frmSendEmail.iEmailType = frmSendEmail.EmailType.Candidate
            '    End If

            '    'Dim currentRowIndex As Integer = grdInbox.SelectedIndex
            '    ' Dim myRow As DataRowView = CType(grdInbox.Items(currentRowIndex), DataRowView)

            '    'frmSendEmail.MdiParent = frmMDIMain
            '    'frmSendEmail.Show()
            '    'If Not People.GetCandidateEmailAddress(GlobalCRM.CurrentCaseID) Is Nothing Then
            '    '        frmSendEmail.txtTo.Text = People.GetCandidateEmailAddress(GlobalCRM.CurrentCaseID).ToString
            '    'End If
            '    'frmSendEmail.txtTo.Text = myRow.Cells(1).Value.ToString      ' this is bringing up the display name, ie "John Smith" instead of the underlying email address
            '    'frmSendEmail.txtSubject.Text = myRow(0).ToString

            '    If chkQuoteMessage.Checked = True Then
            '        sbBody.Append(vbCrLf & vbCrLf & vbCrLf)
            '        sbBody.Append("-----------------------------------------------------------------------------------------------------------" & vbCrLf)
            '        sbBody.Append(vbCrLf)
            '        sbBody.Append("From: " & txtFrom.Text & vbCrLf)
            '        sbBody.Append("To: " & txtTo.Text & vbCrLf)
            '        sbBody.Append("Subject: " & txtSubject.Text & vbCrLf & vbCrLf)
            '        sbBody.Append(Me.txtBody.Text.ToString)

            '        frmSendEmail.txtbody.Text = sbBody.ToString
            '    End If
            '    Me.Dispose()

            'Catch ex As Exception
            'Finally
            '    sbBody = Nothing
            'End Try
        End Sub
    End Class

End Namespace